package com.burton.dp.listener;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.EnsurePath;
import org.apache.zookeeper.CreateMode;

public class NodeCacheDemo {

	static String path = "/zk/nodecache";
	static CuratorFramework client = CuratorFrameworkFactory.builder()
			.connectString("127.0.0.1:2181").sessionTimeoutMs(5000)
			.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

	public static void main(String[] args) throws Exception {
		client.start();

		if (client.checkExists().forPath(path) == null) {
			client.create().creatingParentsIfNeeded()
					.withMode(CreateMode.PERSISTENT)
					.forPath(path, "int".getBytes());
		}
		final NodeCache cache = new NodeCache(client, path, false);
		cache.start();
		cache.getListenable().addListener(new NodeCacheListener() {
			public void nodeChanged() throws Exception {
				System.out.println("node data update ,new data:"
						+ new String(cache.getCurrentData().getData()));

			}
		});
		// 修改节点内容
		client.setData().forPath(path, "b".getBytes());
		synchronized (NodeCacheDemo.class) {
			while (true) {
				try {
					NodeCacheDemo.class.wait();
				} catch (InterruptedException e) {
				}
			}
		}
		// // 删除节点
		// client.delete().deletingChildrenIfNeeded().forPath(path);
		// // 新建节点，触发change
		// client.create().creatingParentsIfNeeded()
		// .withMode(CreateMode.EPHEMERAL).forPath(path, "int".getBytes());
		// Thread.sleep(Integer.MAX_VALUE);
	}

}
